<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Entity_Image extends Core_Db_Entity {

	protected $_width = null;

	protected $_height = null;
	
	protected $_size = null;

	public function __construct() {
		parent::__construct(App::db());
		$this->setBaseTable('image');
	}
	
	public function resize($w=null, $h=null) {
		$this->_width = $w;
		$this->_height = $h;
		return $this;
	}
	
	public function getUrl() {
		$file = $this->getFile();
		if ($this->_width || $this->_height) {
			$cacheDir = $this->getImageDir() . 'cache/' . $this->_width . '_' . $this->_height . '/';
			if (!is_dir($cacheDir))
				mkdir($cacheDir, 0777, true);

			$newFile = 'cache/' . $this->_width . '_' . $this->_height . '/' . $file;
			if (!file_exists($this->getImageDir() . $newFile)) {
				$config['image_library'] = 'gd2';
				$config['source_image'] = $this->getImageDir() . $file;
				$config['new_image'] = $this->getImageDir() . $newFile;
				$config['create_thumb'] = TRUE;
				$config['maintain_ratio'] = TRUE;
				$config['master_dim'] = 'width';
				$config['thumb_marker'] = '';
				
				if (!$this->_width)
					$this->_width = floor($this->_height * $this->getOriginalWidth() / $this->getOriginalHeight());
				else if (!$this->_height)
					$this->_height = floor($this->_width * $this->getOriginalHeight() / $this->getOriginalWidth());

				$config['width'] = $this->_width;
				$config['height'] = $this->_height;

				$imgLib =  App::lib('image_lib');
				$imgLib->initialize($config);
				$imgLib->resize();
			}
			$file = $newFile;
		}
		return App::url() . 'media/post/' . $file;
	}
	
	public function getImageDir() {
		return str_replace('system/','media/post/', BASEPATH);
	}
	
	public function getOriginalWidth() {
		if (!$this->_size)
			$this->_size = getimagesize($this->getImageDir().$this->getFile());
		return $this->_size[0];
	}
	
	public function getOriginalHeight() {
		if (!$this->_size)
			$this->_size = getimagesize($this->getImageDir().$this->getFile());
		return $this->_size[1];
	}
	
	public function getFileName() {
		return $this->getImageDir() . $this->getFile();
	}
}